package cn.gson.springmvc.model.services;

import cn.gson.springmvc.model.Vo.RukuZx;
import cn.gson.springmvc.model.Vo.YaoPinsZx;
import cn.gson.springmvc.model.dao.*;
import cn.gson.springmvc.model.mapper.RukutableMapperZx;
import cn.gson.springmvc.model.pojos.InventoryDetailsEntity;
import cn.gson.springmvc.model.pojos.OutpatientEntity;
import cn.gson.springmvc.model.pojos.PurchasingEntity;
import cn.gson.springmvc.model.pojos.RukutableEntity;
import com.alibaba.fastjson.JSONArray;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;
import java.util.Date;
import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
public class RukutableServicesZx {

    @Autowired
    RukutableMapperZx rukutableMapperZx;
    @Autowired
    PurchasingDaoZx purchasingDaoZx;
    @Autowired
    YaoPinDaoZx yaoPinDaoZx;
    @Autowired
    OutpatientDaoZx outpatientDaoZx;
    @Autowired
    InventoryDetailsDaoZx inventoryDetailsDaoZx;
    @Autowired
    RukutableDaoZx rukutableDaoZx;

    //查询所有采购单
    public JSONArray findAll(){
        return rukutableMapperZx.findAll();
    }

    //根据采购单查询详情
    public JSONArray findAlln(Integer purchasingId){
        return rukutableMapperZx.findAlln(purchasingId);
    }


    //新增
    @Transactional(value = "transactionManager" ,rollbackFor = Exception.class)
    public void shenhexz(RukuZx rukuZx){
        //生成入库审核单
        RukutableEntity rukutable=new RukutableEntity();
        rukutable.setRukutableZongshu(rukuZx.getAmount());
        rukutable.setRukutableRen(rukuZx.getRukur());
        rukutable.setRukutableData(new Timestamp(new Date().getTime()));

        rukutableDaoZx.save(rukutable);

        //生成库存表 //生成详情
        List<YaoPinsZx> yao= rukuZx.getRkyaop();
        for(YaoPinsZx y:yao){
            OutpatientEntity outpatient=new OutpatientEntity();//库存表
            outpatient.setYaopinByYaopinId(yaoPinDaoZx.findById(new Long(y.getYaopinId())).get());
            outpatient.setOutpatientSl(y.getXiangqingSum());
            outpatientDaoZx.save(outpatient);
            InventoryDetailsEntity inv=new InventoryDetailsEntity();//入库详情
            inv.setRukutableByRukutableId(rukutable);
            inv.setOutpatientByOutpatientId(outpatient);
            inv.setInventoryDetailsSl(y.getXiangqingSum());
            inventoryDetailsDaoZx.save(inv);
        }
    }

    //修改审核状态
    @Transactional(value = "transactionManager" ,rollbackFor = Exception.class)
    public void shenhexz(Long purId){
        PurchasingEntity purchasing=purchasingDaoZx.findById(purId).get();
        purchasing.setPurchaseingZuantai(2);
        purchasingDaoZx.save(purchasing);
    }

}
